package cms.web.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

public class TraceIdUtil {

    private static boolean isIpFormat(String ip) {
        return ip != null && ip.length() > 0 && ip.matches("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[0-9])");
    }
    private static List<String> getLocalIps() throws Exception {
        List<String> localIps = new ArrayList();
        Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();

        while(netInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface)netInterfaces.nextElement();
            Enumeration inetAddresses = networkInterface.getInetAddresses();

            while(inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress)inetAddresses.nextElement();
                String ip = inetAddress.getHostAddress();
                if (isIpFormat(ip) && !ip.startsWith("127.")) {
                    localIps.add(ip);
                }
            }
        }

        return localIps;
    }
    /**
     * IP+timeMillis+thread
     * @return
     */
    public static String createTraceId(){
        try {
            List<String> localIps = getLocalIps();
            StringBuilder builder = new StringBuilder();
            builder.append(localIps.get(0).replace(".",""))
                    .append(System.currentTimeMillis()).append(Thread.currentThread().getId());
            return builder.toString();
        }catch (Exception e){
            e.printStackTrace();
            return createUUIDTraceId();
        }
    }

    /**
     * UUID去掉`-`的TraceId
     * @return
     */
    public static String createUUIDTraceId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    public static void main(String[] args) {

        System.out.println("TraceIdUtil.main"+TraceIdUtil.createTraceId());

    }
}
